# Contributor: Carlo Landmeter <clandmeter@alpinelinux.org>
# Maintainer: Natanael Copa <ncopa@alpinelinux.org>
pkgname=libjpeg-turbo
pkgver=3.0.4
pkgrel=0
pkgdesc="Accelerated baseline JPEG compression and decompression library"
url="https://libjpeg-turbo.org/"
arch="all"
license="BSD-3-Clause AND IJG AND Zlib"
makedepends="cmake nasm samurai"
replaces="libjpeg"
subpackages="$pkgname-static $pkgname-doc $pkgname-dev libturbojpeg $pkgname-utils"
source="https://github.com/libjpeg-turbo/libjpeg-turbo/releases/download/$pkgver/libjpeg-turbo-$pkgver.tar.gz"

# secfixes:
#   2.1.5.1-r4:
#     - CVE-2023-2804
#   2.1.0-r0:
#     - CVE-2021-20205
#   2.0.6-r0:
#     - CVE-2020-35538
#   2.0.4-r2:
#     - CVE-2020-13790
#   2.0.4-r0:
#     - CVE-2019-2201
#   2.0.2-r0:
#     - CVE-2018-20330
#     - CVE-2018-19664
#   1.5.3-r3:
#     - CVE-2018-11813
#   1.5.3-r2:
#     - CVE-2018-1152

build() {
	local _floattest=
	if [ "$CBUILD" != "$CHOST" ]; then
		CMAKE_CROSSOPTS="-DCMAKE_SYSTEM_NAME=Linux -DCMAKE_HOST_SYSTEM_NAME=Linux"
	fi
	case "$CARCH" in
		ppc64le) export JSIMD_FORCENONE=1;;
		s390x|riscv64) _floattest="-DFLOATTEST=fp-contract";;
	esac

	CFLAGS="$CFLAGS -O2 -DNDEBUG -flto=auto" \
	CXXFLAGS="$CXXFLAGS -O2 -DNDEBUG -flto=auto" \
	cmake -B build-shared -G Ninja \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DCMAKE_INSTALL_LIBDIR=/usr/lib \
		-DBUILD_SHARED_LIBS=True \
		-DENABLE_STATIC=False \
		-DCMAKE_BUILD_TYPE=None \
		-DCMAKE_SKIP_INSTALL_RPATH=ON \
		-DWITH_JPEG8=1 \
		$_floattest \
		$CMAKE_CROSSOPTS
	cmake --build build-shared

	cmake -B build-static -G Ninja \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DCMAKE_INSTALL_LIBDIR=/usr/lib \
		-DBUILD_SHARED_LIBS=False \
		-DENABLE_STATIC=True \
		-DCMAKE_BUILD_TYPE=None \
		-DCMAKE_SKIP_INSTALL_RPATH=ON \
		-DWITH_JPEG8=1 \
		$_floattest \
		$CMAKE_CROSSOPTS
	cmake --build build-static
}

check() {
	cd build-shared
	# random checksum failures
	ctest -E '(djpeg-shared-3x2-float-prog-cmp|example-12bit-shared-decompress-cmp)'
}

package() {
	DESTDIR="$pkgdir" cmake --install build-static
	DESTDIR="$pkgdir" cmake --install build-shared
	install -d "$pkgdir"/usr/share/licenses/$pkgname
	ln -s ../../doc/libjpeg-turbo/LICENSE.md "$pkgdir/usr/share/licenses/$pkgname"
}

utils() {
	pkgdesc="Utilities for manipulating JPEG images"
	replaces="jpeg"

	amove usr/bin
}

libturbojpeg() {
	amove usr/lib/libturbojpeg.so.*
}

doc() {
	default_doc
	replaces="jpeg-doc"
}

dev() {
	default_dev
	replaces="jpeg-dev"
}

sha512sums="
04d37d65131f7ab8586507fe6520452e791e9b8d72a08cf52f81279450b4c6b8a5b49ff3e14e358d3c32cb5666b6d4576d1e16895af8213a1761464de5dc9d31  libjpeg-turbo-3.0.4.tar.gz
"
